<template>
  <el-select v-model="input" clearable placeholder="请选择">
    <el-option v-if="options.length" label="全部" value=""></el-option>
    <el-option
      v-for="item in options"
      :key="item[valName]"
      :label="item[keyName]"
      :value="item[valName]">
    </el-option>
  </el-select>
</template>
<script>
import { listArea } from '@/api/base/area'
import { listBuild } from '@/api/base/build'
import { listSchool } from '@/api/base/school'
import { listFloor } from '@/api/base/floor'
export default {
  name: "FusionSelect",
  props: {
    value: String,
    keyName: {
      type: String,
      default: 'name'
    },
    valName: {
      type: String,
      default: 'id'
    },
    type: {
      type: String,
      required: true
    },
    paramsVal: {
      type: String,
      default: null
    },
    paramsKey: {
      type: String,
      default: null
    },
    instantly: {
      type: Boolean,
      default: true
    }
  },
  model: {
    prop: 'value',        // 指定 v-model 要绑定的参数叫什么名字，来自于 props 中定义的参数
    event: 'change',    // 指定要触发的事件名字，将被用于 $emit
  },
  computed: {
    input: {
      // 这里的计算属性使用了 getter、setter，可以简化代码
      // 可参见链接 https://cn.vuejs.org/v2/guide/computed.html#%E8%AE%A1%E7%AE%97%E5%B1%9E%E6%80%A7%E7%9A%84-setter
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('change', val);    // 触发
      }
    }
  },
  data() {
    return {
      options: [],
    }
  },
  watch: {
    paramsVal: {
      deep: true,
      immediate: true,
      handler(val) {
        if(this.instantly) {
          this.getList()
        } else {
          if(val) {
            this.getList()
          } else {
            this.options = []
            this.input = null
          }
        }
      }
    }
  },
  created() {
    // if(this.instantly) this.getList()
  },
  methods: {
    getList() {
      const urls = {
        area: listArea,
        school: listSchool,
        build: listBuild,
        floor: listFloor
      }
      const params = {
        pageSize: 99999,
        pageNum: 1
      }
      if(this.paramsKey) {
        params[this.paramsKey] = this.paramsVal
      }
      urls[this.type](params).then(response => {
        this.options = response.data || response.rows || [];
      })
    }
  }
}
</script>